package cn.zsb.web;

import cn.zsb.entity.Advtise;
import cn.zsb.service.AdvtiseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author oldliu
 * @since 1.0
 */
@Controller
@RequestMapping("adv")
public class AdvtiseController {
    
    @Autowired
    private AdvtiseService advtiseService;
    
    @PostMapping("add")
    public String add(Advtise adv, @RequestParam(name = "a_imgurl",required = false) MultipartFile file, HttpServletRequest request){
        if(!file.isEmpty()){
            String path = request.getServletContext().getRealPath("img");
            File f = new File(path);
            if(!f.exists())
                f.mkdir();
            //原来的文件名
            String filename = file.getOriginalFilename();
            String houzhui = filename.substring(filename.lastIndexOf('.'));
            String newName= UUID.randomUUID()+houzhui;
            adv.setImgurl(newName);
            try {
                file.transferTo(new File(f,newName));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        advtiseService.add(adv);
        return "redirect:/adv/get/"+adv.getId();
    }
    @GetMapping("get/{id}")
    public String toAdd(@PathVariable long id, Model m){
        Advtise ad = this.advtiseService.get(id);
        m.addAttribute("adv",ad);
        return "advtise";
    }
    @GetMapping("toAdd")
    public String toAdd(){
        return "addAdv";
    }
}
